package com.algorithm.Utils.commonUtils;

import com.algorithm.example.stack.LinkedListStack;
import org.springframework.stereotype.Component;

import java.util.LinkedList;
import java.util.Random;

/**
 * <p>
 *
 * </p>
 *
 * @author lzt
 * @version 1.0
 * @since 2024/1/21 23:03
 */
@Component
public class CommonUtils {

    public static void print(LinkedList<Integer> a, LinkedList<Integer> b, LinkedList<Integer> c) {
        System.out.println(a);
        System.out.println(b);
        System.out.println(c);
        System.out.println("---------------------");
    }

    public static void print(int n, int i) {
        int m = (n - 1 - i) * 2;
        for (int j = 0; j < m; j++) {
            System.out.print(" ");
        }
    }

    /**
     * 生成随机数组
     */
    public static int[] generateRandomArray(int size) {
        int[] array = new int[size];
        Random random = new Random();

        for (int i = 0; i < size; i++) {
            array[i] = random.nextInt();
        }

        return array;
    }

    /**
     * 符号优先级
     * @param c 判断的符号
     * @return 返回级数
     */
    public static int priority(char c) {
        return switch(c) {
            case '*','/' -> 2;
            case '+','-' -> 1;
            case '(' -> 0;
            default -> throw new RuntimeException("出错");
        };
    }


    /**
     * 中缀表达式  ->  后缀表达式
     * 1 + 2 * 1 ->  1  2  1 * +
     * 1 + 2 - 1 ->  1  2 + 1 -
     * @param exp 待转化的字符
     * @return 转换完成的字符
     */
    public static String infixToSuffix(String exp) {
        LinkedListStack<Character> characters = new LinkedListStack<Character>(exp.length());
        StringBuilder str = new StringBuilder();
        for (int i = 0; i < exp.length(); i++) {
            char c = exp.charAt(i);
            switch (c) {
                case '*','/','+','-' -> {
                    if(characters.isEmpty()) {
                        characters.push(c);
                    } else {
                        if(priority(c) <= priority(characters.peek())) {
                            while (!characters.isEmpty() && priority(c) <= priority(characters.peek())) {
                                str.append(characters.pop());
                            }
                            characters.push(c);
                        } else {
                            characters.push(c);
                        }
                    }
                }
                case '(' -> {
                    characters.push(c);
                }
                case ')' -> {
                    while (!characters.isEmpty() && characters.peek() != '(') {
                        str.append(characters.pop());
                    }
                    characters.pop();
                }
                default -> str.append(c);

            }
        }
        while (!characters.isEmpty()) {
            str.append(characters.pop());
        }
        return str.toString();
    }


}
